package geometry;

import hulppakket.Point3f;
import hulppakket.Ray;

public class BoundingBox {

	private Point3f min, max;

	public BoundingBox(Point3f min, Point3f max) {
		this.min = min;
		this.max = max;
	}

	public BoundingBox combine(BoundingBox other) {
		float x, y, z;
		x = Math.min(this.getMin().x, other.getMin().x);
		y = Math.min(this.getMin().y, other.getMin().y);
		z = Math.min(this.getMin().z, other.getMin().z);
		Point3f min = new Point3f(x, y, z);
		x = Math.max(this.getMax().x, other.getMax().x);
		y = Math.max(this.getMax().y, other.getMax().y);
		z = Math.max(this.getMax().z, other.getMax().z);
		Point3f max = new Point3f(x, y, z);
		return new BoundingBox(min, max);
	}

	public Point3f getMax() {
		return this.max;
	}

	public Point3f getMin() {
		return this.min;
	}

	public boolean hit(Ray ray, float t0, float t1) {
		float txmin, txmax, tymin, tymax, tzmin, tzmax, d;

		d = 1 / ray.getDirection().x;
		if (d >= 0) {
			txmin = (min.x - ray.getOrigin().x) * d;
			txmax = (max.x - ray.getOrigin().x) * d;
		} else {
			txmin = (max.x - ray.getOrigin().x) * d;
			txmax = (min.x - ray.getOrigin().x) * d;
		}

		d = 1 / ray.getDirection().y;
		if (d >= 0) {
			tymin = (min.y - ray.getOrigin().y) * d;
			tymax = (max.y - ray.getOrigin().y) * d;
		} else {
			tymin = (max.y - ray.getOrigin().y) * d;
			tymax = (min.y - ray.getOrigin().y) * d;
		}
		d = 1 / ray.getDirection().z;
		if (d >= 0) {
			tzmin = (min.z - ray.getOrigin().z) * d;
			tzmax = (max.z - ray.getOrigin().z) * d;
		} else {
			tzmin = (max.z - ray.getOrigin().z) * d;
			tzmax = (min.z - ray.getOrigin().z) * d;
		}

		if (txmin > tymax || tymin > txmax || txmin > tzmax || tzmin > txmax
				|| tzmin > tymax || tymin > tzmax)
			return false;
		return true;
	}

	public void setMax(Point3f max) {
		this.max = max;
	}

	public void setMin(Point3f min) {
		this.min = min;
	}
}
